package org.example.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request1 = (HttpServletRequest) request;
        String[] urls ={"/login.html","/Login","/register.html","/Register"};
        String requestURL = request1.getRequestURL().toString();

        System.out.println(requestURL);
        for (String url : urls) {
            if(requestURL.contains(url)){
                chain.doFilter(request,response);
                return;
            }

        }

        HttpSession session = request1.getSession();
        Object user = session.getAttribute("user");
        //判断session中是否有user
        if(user != null){
            //登录过了
            chain.doFilter(request, response);
        }else{
            //没有登录

            request1.getRequestDispatcher("/login.html").forward(request,response);
        }


    }
}
